package com.cloudcross.ssp.service.impl;

import com.cloudcross.ssp.base.dao.GenericIBatisDao;
import com.cloudcross.ssp.common.Config;
import com.cloudcross.ssp.common.utils.Common;
import com.cloudcross.ssp.common.utils.MapBuilder;
import com.cloudcross.ssp.common.utils.Pager;
import com.cloudcross.ssp.common.utils.SqlHelper;
import com.cloudcross.ssp.model.Account;
import com.cloudcross.ssp.model.Banner;
import com.cloudcross.ssp.model.BannerTemplate;
import com.cloudcross.ssp.model.Log;
import com.cloudcross.ssp.service.IBannerService;
import com.cloudcross.ssp.service.ILogService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BannerService implements IBannerService {

    private Logger LOG = LogManager.getLogger(getClass());
    @Autowired
    private GenericIBatisDao myBatisDao;
    @Autowired
    ILogService logService;
    @Autowired
    Config config;

    @Override
    public Banner findById(Long id) {
        return myBatisDao.get("bannerSqlMapper.findByIdAdvertiser", id);
    }

    @Override
    public int countByParams(Map<String, Object> paramMap) {
        // 这里的搜索只是对名称进行搜索
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        return myBatisDao.get("bannerSqlMapper.countByParams", paramMap);
    }

    @Override
    public List<Banner> findByParams(Map<String, Object> paramMap, Pager pager) {
        String searchValue = SqlHelper.doLike(paramMap.get("searchValue"));
        paramMap.put("key", paramMap.get("searchKey"));
        paramMap.put("value", searchValue);
        paramMap.put("pager", pager);
        return myBatisDao.getList("bannerSqlMapper.findByParams", paramMap);
    }

    // 新增创意，只新增一条创意记录 djp
    @Override
    public boolean add(Banner t) {
        Date date = new Date();
        t.setUpdated(date);
        t.setSupdated(date.getTime() / 1000);
        myBatisDao.save("bannerSqlMapper.addBanner", t);
        return true;
    }

    // 编辑创意 djp
    @Override
    public boolean edit(Banner t) {
        Date date = new Date();
        t.setUpdated(date);
        t.setSupdated(date.getTime() / 1000);
        t.getBannerTemplate().setUpdated(date);
        myBatisDao.save("bannerSqlMapper.editBanner", t);
        return true;
    }

    // 更新创意 djp
    @Override
    public boolean updata(Banner t) {
        Date date = new Date();
        Long supdated = date.getTime() / 1000;
        t.setUpdated(date);
        t.setSupdated(supdated);
        t.getBannerTemplate().setUpdated(date);
        myBatisDao.save("bannerSqlMapper.updataBanner", t);
        Long id[] = { t.getId() };
        myBatisDao.save("bannerSqlMapper.updataOperatorBanner", MapBuilder.create(HashMap.class).add("idList", id).add("supdated", supdated).map());

        return true;
    }

    @Override
    public boolean edit(Map<String, Object> paramMap) {
        return true;
    }

    // 批量改变状态 djp
    @Override
    public boolean updateStatus(List<Long> idList, int status) {
        Date date = new Date();
        Long supdated = date.getTime() / 1000;
        // 更新创意与创意模板状态
        myBatisDao.save("bannerSqlMapper.updateBannerStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("updated", date).add("supdated", supdated).map());
        if (status == -1) {
            myBatisDao.save("bannerSqlMapper.updataDeleteBannerOperatorStatus",
                    MapBuilder.create(HashMap.class).add("idList", idList).add("supdated", supdated).map());
        } else {
            myBatisDao.save("bannerSqlMapper.updataOperatorBanner",
                    MapBuilder.create(HashMap.class).add("idList", idList).add("supdated", supdated).map());
        }
        return true;
    }

    @Override
    public int countByAdGroupId(Long adGroupId) {
        return myBatisDao.get("bannerSqlMapper.countByAdGroupId", adGroupId);
    }

    @Override
    public boolean cloneBanner(Map<String, Object> paramMap) {
        // 查询模板
        Long bannerTemplateId = (Long) paramMap.get("bannerTemplateId");
        BannerTemplate bannerTemplate = myBatisDao.get("bannerTemplateSqlMapper.findById", bannerTemplateId);
        bannerTemplate.setAdvertiserId((Long) paramMap.get("advertiserId"));
        bannerTemplate.setAgentId((Long) paramMap.get("agentId"));
        myBatisDao.save("bannerTemplateSqlMapper.updataIds", bannerTemplate);

        Banner banner = new Banner();
        // 设置新建创意信息
        banner.setBannerTemplateId((Long) paramMap.get("bannerTemplateId"));
        banner.setAdGroupId((Long) paramMap.get("adGroupId"));
        banner.setOrderId((Long) paramMap.get("orderId"));
        banner.setVisitAddress("");
        banner.setClickAddress("");
        banner.setImpressionAddress("");
        banner.setMemo("");
        banner.setChecked(0);
        banner.setStatus(bannerTemplate.getStatus());
        Date date = new Date();
        Long supdated = date.getTime() / 1000;
        banner.setUpdated(date);
        banner.setSupdated(supdated);
        banner.setBannerTemplate(bannerTemplate);

        myBatisDao.save("bannerSqlMapper.addBanner", banner);

        /**
         * 创意添加成功之后要增加日志记录
         */
        HttpServletRequest request = (HttpServletRequest) paramMap.get("request");
        Account account = (Account) paramMap.get("account");
        Log log = new Log();
        // 对应模块，这里应该是投放模块
        log.setModule("Ad");
        // 对应的表名，这里是t_adgroup
        log.setTableName("t_banner");
        // 对应的投放id
        log.setRecordId(banner.getId());
        // 对应的操作类型
        log.setActionType("新增");
        // 变更详情
        log.setAction("新增了创意：" + bannerTemplate.getName());
        log.setActionTime("100");
        log.setAccountId(new Long(account.getId()));
        log.setUserIp(Common.toIpAddr(request));
        log.setAccountName(account.getAccountName());
        logService.add(log);

        return true;
    }

    // 根据adGroupId更新banner的supdated时间
    @Override
    public boolean updateSupdated(List<Long> adGroupIdList, Date date) {
        myBatisDao.save("bannerSqlMapper.updateBannerSupdated",
                MapBuilder.create(HashMap.class).add("adGroupIdList", adGroupIdList).add("modifyDate", date.getTime() / 1000).map());
        return true;
    }

    @Override
    public boolean updateSupdatedByOrderId(List<Long> orderIdList, Date date) {
        myBatisDao.save("bannerSqlMapper.updateBannerSupdatedByOrderId",
                MapBuilder.create(HashMap.class).add("orderIdList", orderIdList).add("modifyDate", date.getTime() / 1000).map());

        return true;
    }

    @Override
    public boolean updateStatusByOrderId(List<Long> orderIdList, int status) {
        myBatisDao.save("bannerSqlMapper.updateStatusByOrderId",
                MapBuilder.create(HashMap.class).add("orderIdList", orderIdList).add("modifyDate", new Date()).add("status", status).map());

        return true;
    }

    @Override
    public boolean updateStatusByAdGroupId(List<Long> adGroupIdList, int status) {
        myBatisDao.save("bannerSqlMapper.updateStatusByAdGroupId",
                MapBuilder.create(HashMap.class).add("adGroupIdList", adGroupIdList).add("modifyDate", new Date()).add("status", status).map());

        return true;
    }

    @Override
    public int countByParams1(Map<String, Object> paramMap) {
        return myBatisDao.get("bannerSqlMapper.countByParams1", paramMap);
    }

    @Override
    public List<Banner> findByParams1(Map<String, Object> paramMap, Pager pager) {
        paramMap.put("pager", pager);
        return myBatisDao.getList("bannerSqlMapper.findByParams1", paramMap);
    }

    @Override
    public List<Banner> findByParams1(Map<String, Object> paramMap) {
        return myBatisDao.getList("bannerSqlMapper.findByParams2", paramMap);
    }

    @Override
    public boolean updateStatus1(List<Long> idList, int status) {
        Date date = new Date();
        Long supdated = date.getTime() / 1000;
        myBatisDao.save("bannerSqlMapper.updateBannerStatus",
                MapBuilder.create(HashMap.class).add("status", status).add("idList", idList).add("updated", date).add("supdated", supdated).map());
        if (status == -1) {
            myBatisDao.save("bannerSqlMapper.updataDeleteBannerOperatorStatus",
                    MapBuilder.create(HashMap.class).add("idList", idList).add("supdated", supdated).map());
        } else {
            myBatisDao.save("bannerSqlMapper.updateOperatorBannerTime",
                    MapBuilder.create(HashMap.class).add("idList", idList).add("supdated", supdated).map());
        }
        return true;
    }

    @Override
    public void updateBannerUrlByCondition(List<Long> idList, String click, String impression, String visit) {
        myBatisDao.save("bannerSqlMapper.updateBannerByCondition",
                MapBuilder.create(HashMap.class).add("idList", idList).add("click", click).add("impression", impression).add("visit", visit).map());
    }

    @Override
    public List<Long> queryBannerIdByAdgroupId(Long adgroupId) {
        return myBatisDao.getList("bannerSqlMapper.queryBannerIdByAdgroupId", adgroupId);
    }

    /**
     * orderId 目的订单ID oldadgroupId 原策略ID newadgroupId 新策略ID supdated 更新时间
     */
    @Override
    public boolean copyBannerBetch(long orderId, long oldadgroupId, long newadgroupId, long supdated) {
        Map<String, Object> condition = new HashMap<String, Object>();
        condition.put("orderId", orderId);
        condition.put("oldadgroupId", oldadgroupId);
        condition.put("newadgroupId", newadgroupId);
        condition.put("supdated", supdated);
        myBatisDao.save("bannerSqlMapper.copyBannerBetch", condition);
        return true;
    }

	@Override
	public int getBannerCountByAdgroupId(Long adgroupId) {
		return myBatisDao.get("bannerSqlMapper.getBannerCountByAdgroupId", adgroupId);
	}

	@Override
	public List<Banner> getBannerListByAdGroupId(Long adGroupId) {
		return myBatisDao.getList("bannerSqlMapper.getBannerListByAdGroupId", adGroupId);
	}
}